/**
 * mrz码识别参考
 * https://www.cnblogs.com/catzhou/p/12711979.html
 * @constructor
 */
const os = require('os')
const crypto = require('crypto')
const { execSync } = require('child_process')
function CommonUtil(){
    /**
     * 睡眠ms毫秒
     * @param ms
     * @returns {Promise<unknown>}
     */
    this.sleep = function (ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }

    this.getMachineId = function() {
        let machineId = ''
        const machineInfo = this.getMachineInfo()
        /*if(machineInfo.cpuSerial || machineInfo.diskSerial){
            machineId = machineInfo.cpuSerial + machineInfo.diskSerial
        }else{
            machineId = machineInfo.mac + machineInfo.arch + machineInfo.endianness
        }*/
        machineId = machineInfo.diskSerial

        const hash = crypto.createHash('sha256');
        hash.update(machineId);
        return hash.digest('hex');
    }

    this.getMachineInfo = function () {
        var machineInfo = {}
        if(os.platform() === 'win32') {
            // 获取硬盘序列号
            const disks = execSync('wmic diskdrive get serialnumber').toString().split('\n').slice(1, -1)
            const diskSerials = disks.map(serial => serial.trim())
            machineInfo.diskSerial = diskSerials[0].trim()

            // 获取CPU序列号
            const cpu = execSync('wmic cpu get processorid').toString().split('\n').slice(1, -1)
            const cpuSerial = cpu[0].trim();
            machineInfo.cpuSerial = cpuSerial
        }
        const networkInterfaces = os.networkInterfaces();
        for (const key in networkInterfaces) {
            networkInterfaces[key].forEach(function (ni) {
                if (ni.family === 'IPv4' && !ni.internal) {
                    machineInfo.mac= ni.mac
                }
            })
        }
        //操作系统的主机名
        machineInfo.hostname = os.hostname()
        //CPU 的字节序
        machineInfo.endianness = os.endianness()
        //操作系统名
        machineInfo.platform = os.platform()
        //cpu架构
        machineInfo.arch = os.arch()

        console.log('machineInfo', machineInfo)
        return machineInfo
    }

    /**
     * 生成注册码
     * @returns {string}
     */
    this.createRegistCode = function () {
        var machineId = this.getMachineId();
        return machineId.substr(0, 10)
    }

    this.md5 = function (str) {
        return crypto.createHash('md5').update(str).digest('hex')
    }
}

export default new CommonUtil()
